import java.util.*  ;

public class Text {
    public List<List<Integer>> threeSum(int[] nums) {
        List<List<Integer>> ret = new ArrayList<>();
        Arrays.sort(nums);
        int len = nums.length;
        if(nums[0] > 0 || len < 3) {
            return ret;
        }
        for(int i = 0;i < len;i++) {
            if(nums[i] > 0) break;
            if(i>0 && nums[i] == nums[i-1]) continue;
            int L = i+1;
            int R = len-1;
            while(L < R) {
                int sum = nums[i] + nums[L] + nums[R];
                if(sum == 0) {
                    List<Integer> cur = new ArrayList<>();
                    cur.add(nums[i]);
                    cur.add(nums[L]);
                    cur.add(nums[R]);
                    ret.add(cur);
                    while(L < R && nums[R] == nums[R-1]) R--;
                    while(L < R && nums[L] == nums[L+1]) L++;
                    R--;
                    L++;
                }
                else if(sum > 0) R--;
                else if(sum < 0) L++;
            }
        }
        return ret;
    }
}
